package com.jhx.video.publish

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.model.Event
import com.jhx.common.model.Video
import com.jhx.common.thirdparty.db.DBHelper
import com.jhx.common.utils.UserManager
import com.jhx.common.utils.centerToast
import com.jhx.common.utils.customToast
import com.jhx.common.widget.CommonDialog
import com.jhx.video.R
import com.jhx.video.model.Bonus
import com.jhx.video.videoupload.TXUGCPublishTypeDef
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.android.synthetic.main.fragment_publish_video.*
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * 发布页面
 *
 * @author Jack 2018-03-08 18:51
 */
class VideoPublishFragment : QuickBaseFragment(), Contract.PublishView {
    private var mFromPage: Int? = 0
    private var mDuration: String? = ""
    private var mVideo: Video? = null
    private var mCoverPath: String? = null
    private var mVideoPath: String? = null
    private var mTipTxt: TextView? = null
    private var mMoneyTxt: TextView? = null
    private var mConfirmTxt:TextView? = null
    private var mDialog: CommonDialog? = null
    private var mPublishDialog: Dialog? = null
    private var mTextContent: String? = null
    private var mPresenter: PublishPresenterImpl? = null
    private val mVideoList: ArrayList<Video> = ArrayList()

    companion object {
        val KEY_FROM = "form_page"
        val VIDEO_DATA = "video_data"
        val FROM_DRAFT = 1
    }

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_publish_video, container, false)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mFromPage = arguments?.getInt(KEY_FROM)
        mVideo = arguments?.getSerializable(VIDEO_DATA) as Video
        mCoverPath = mVideo?.cover_url
        mVideoPath = mVideo?.video_url
        mDuration = mVideo?.countTime
        mTextContent = mVideo?.context
        mPresenter = PublishPresenterImpl()
        mPresenter?.setView(this)
        txt_publish.setOnClickListener {
            if(TextUtils.isEmpty(edit_desc.text.toString())) {
                activity?.centerToast("请输入视频描述")
                return@setOnClickListener
            }
            mPresenter?.getSign()
        }
        try {
            val file = File("$mCoverPath")
            Glide.with(activity).load(file).into(videoview)
        } catch (e: Exception) {
            CrashReport.postCatchedException(e)
        }
        edit_desc.addTextChangedListener(object: TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                txt_count.text = "${edit_desc.text.length}/120"
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })
        if(!TextUtils.isEmpty(mVideo?.context)) {
            edit_desc.setText("${mVideo?.context}")
            txt_count.text = "${mVideo?.context?.length}/120"
        }
        setTitle("发布视频")
        setMenuText("保存草稿")
        mPresenter?.queryAll()
    }

    override fun showLoading() {
        showLoadingDialog("上传中......")
    }

    override fun hideLoading() {
        hideLoadingDialog()
    }

    override fun getSignSuccess(sign: String?) {
        mPresenter?.publishVideo(sign, mCoverPath, mVideoPath)
    }

    override fun publishSuccess(result: TXUGCPublishTypeDef.TXPublishResult?) {
        delVideo()
        mPresenter?.reportServer(edit_desc.text.toString(),
                result?.videoURL,
                result?.coverURL,
                result?.videoId,
                mDuration)
    }

    override fun getVideoList(list: List<Video>?) {
        mVideoList.clear()
        if(list != null && list.isNotEmpty()) {
            mVideoList.addAll(list)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun reportServerSuccess(data: Bonus?) {
        if(data?.isShow == Bonus.TYPE_SHOW) {
            if(mPublishDialog == null) {
                mPublishDialog = Dialog(activity)
                val view = LayoutInflater.from(activity).inflate(R.layout.dialog_publish_success, null)
                mTipTxt = view.findViewById(R.id.txt_tip)
                mMoneyTxt = view.findViewById(R.id.txt_money)
                mConfirmTxt = view.findViewById(R.id.txt_confirm)
                mConfirmTxt?.setOnClickListener {
                    val event = Event()
                    event.code = Video.CODE_POST_SUCCESS
                    EventBus.getDefault().post(event)
                    mPublishDialog?.dismiss()
                    pop()
                }
                mPublishDialog?.setContentView(view)
                mPublishDialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
            }
            mMoneyTxt?.text = "${data.sendSilver}元"
            mTipTxt?.text = "${data.tips}"
            if(mPublishDialog?.isShowing == false && activity?.isFinishing == false) {
                mPublishDialog?.show()
            }
        } else {
            val view = LayoutInflater.from(activity).inflate(R.layout.view_toast, null)
            val msgText = view.findViewById<TextView>(R.id.txt_message)
            val statusImage = view.findViewById<ImageView>(R.id.img_status)
            msgText.text = "发布成功~"
            statusImage.setImageDrawable(resources.getDrawable(R.mipmap.icon_publish_success))
            activity?.customToast(view)
            val event = Event()
            event.code = Video.CODE_POST_SUCCESS
            EventBus.getDefault().post(event)
            Handler().postDelayed({
                pop()
            }, 1000)
        }
    }

    override fun getContext(): Activity? {
        return activity
    }

    override fun publishError(code: Int, msg: String?) {
        hideLoadingDialog()
        val view = LayoutInflater.from(activity).inflate(R.layout.view_toast, null)
        val msgText = view.findViewById<TextView>(R.id.txt_message)
        val statusImage = view.findViewById<ImageView>(R.id.img_status)
        msgText.text = "发布失败，请稍后重试~"
        statusImage.setImageDrawable(resources.getDrawable(R.mipmap.img_publish_error))
        activity?.customToast(view)
    }

    /**
     * 删除视频文件
     */
    private fun delVideo() {
        val delTask = @SuppressLint("StaticFieldLeak")
        object : AsyncTask<Void, String, Void>() {
            override fun doInBackground(vararg params: Void?): Void? {
                val coverFile = File("$mCoverPath")
                if (coverFile.exists()) {
                    coverFile.delete()
                }
                if (mVideoList.isNotEmpty()) {
                    mVideoList.filter { it.id == mVideo?.id }
                            .map {
                                DBHelper.delData(Video::class.java, it)
                                if (!checkbox_save.isChecked) {
                                    val videoFile = File("$mVideoPath")
                                    if (videoFile.exists()) {
                                        videoFile.delete()
                                    }
                                }
                            }
                }
                return null
            }
        }
        delTask.execute()
    }

    override fun interceptionBack(): Boolean {
        return true
    }

    override fun onBackPressed() {
        if (mFromPage == FROM_DRAFT && mTextContent == edit_desc.text.toString()) {
            pop()
            return
        }
        if(mDialog == null && activity?.isFinishing == false) {
            mDialog = CommonDialog(activity)
        }
        mDialog?.setTitle("是否放弃发布？")
        mDialog?.setCancelBtn("保存草稿")
        mDialog?.setConfirmBtn("返回")
        mDialog?.setOnClickListener(object: CommonDialog.OnClickListener {
            override fun onConfirmClick(view: View?) {
                pop()
            }

            override fun onCancelClick(view: View?) {
                saveVideo()
            }

        })
        if(mDialog?.isShowing == false && activity?.isFinishing == false) {
            mDialog?.show()
        }
    }

    override fun showToolbar(): Boolean {
        return true
    }

    override fun onMenuClick(view: View?) {
        super.onMenuClick(view)
        saveVideo()
    }

    /**
     * 保存视频
     */
    private fun saveVideo() {
        val event = Event()
        if(mFromPage == FROM_DRAFT) {
            mVideoList.filter { it.id == mVideo?.id }
                    .map {
                mVideo?.video_url = mVideoPath
                mVideo?.cover_url = mCoverPath
                mVideo?.countTime = "$mDuration"
                mVideo?.user_id = UserManager.get().user.dmId.toString()
                mVideo?.context = edit_desc.text.toString()
                mVideo?.create_time = System.currentTimeMillis()
                DBHelper.upDate(Video::class.java, mVideo)
                event.code = Video.CODE_UPDATE
            }
        } else {
            val video = Video()
            video.video_url = mVideoPath
            video.cover_url = mCoverPath
            video.countTime = "$mDuration"
            video.user_id = UserManager.get().user.dmId.toString()
            video.context = edit_desc.text.toString()
            video.create_time = System.currentTimeMillis()
            video.id = System.currentTimeMillis().toString()
            DBHelper.addData(Video::class.java, video)
            event.code = Video.CODE_ADD
        }
        EventBus.getDefault().post(event)
        val view = LayoutInflater.from(activity).inflate(R.layout.view_toast, null)
        val msgText = view.findViewById<TextView>(R.id.txt_message)
        val statusImage = view.findViewById<ImageView>(R.id.img_status)
        msgText.text = "已保存到草稿箱~"
        statusImage.setImageDrawable(resources.getDrawable(R.mipmap.icon_publish_success))
        activity?.customToast(view)
        Handler().postDelayed({
            pop()
        }, 1000)
    }

    override fun onDestroyView() {
        mPresenter?.recycler()
        super.onDestroyView()
    }
}